<?php


namespace App\Helper;


use App\Contracts\LoggerInterface;
use Hyperf\Utils\ApplicationContext;
use Psr\SimpleCache\InvalidArgumentException;

class Cache extends \Hyperf\Cache\Cache
{
    /**
     * @param string $key
     * @param int $ttl
     * @param callable $callback
     * @return mixed
     */
    public function remember(string $key, int $ttl, callable $callback)
    {
        try {
            $value = $this->get($key);
            if (is_null($value)) {
                $value = call_user_func($callback);
                $this->set($key, $value, $ttl);
            }
            return $value;
        } catch (InvalidArgumentException $e) {
            ApplicationContext::getContainer()->get(LoggerInterface::class)->critical($e, sprintf('Cache remember(%s)', $key));
        }
    }

    /**
     * @param string $key
     * @param int $ttl
     * @param callable $callback
     * @return mixed
     */
    public function rememberIf(string $key, int $ttl, callable $callback)
    {
        try {
            $value = $this->get($key);
            if (is_null($value)) {
                $value = call_user_func($callback);
                if ($value) {
                    $this->set($key, $value, $ttl);
                }
            }
            return $value;
        } catch (InvalidArgumentException $e) {
            ApplicationContext::getContainer()->get(LoggerInterface::class)->critical($e, sprintf('Cache rememberIf(%s)', $key));
        }
    }
}